import java.util
        .ArrayList;
import java.util
        .concurrent.ExecutorService;


import java.util
        .concurrent.Executors;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author shilinghuai
 * @create 2022/5/30
 * @since 1.0.0
 */
public class ProduceConsumer {
    public static class Bread{

    }
    public static class MyCollection<T>{
        public  ArrayList<T> list =new ArrayList<>();
        public synchronized   void put(T t) throws InterruptedException {
            while (list.size()>10){
                this.wait();
            }
            list.add(t);
            this.notifyAll();
        }
        public synchronized T get() throws InterruptedException {
            while (list.size()==0){
                this.wait();
            }
            T t= list.get(0);
            list.remove(0);
            this.notifyAll();
            return t;
        }
    }
    public static class BreadProducter implements Runnable{
        public MyCollection<Bread> myCollection = null;
        public BreadProducter(MyCollection myCollection){
            this.myCollection = myCollection;
        }

        public
        void run() {
            while (true){
                Bread bread = new Bread();

                try {
                    myCollection.put(bread);
                    System.out.println("生产面包");
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static class BreadConsumer implements Runnable{
        public MyCollection<Bread> myCollection = null;
        public BreadConsumer(MyCollection myCollection){
            this.myCollection = myCollection;
        }

        @Override
        public
        void run() {
            try {
                while (true){
                    Bread bread = myCollection.get();
                    System.out.println("消费面包");
                }

            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args){
        MyCollection myCollection = new MyCollection();
        BreadProducter breadProducter = new BreadProducter(myCollection);
        BreadProducter breadProducter1 = new BreadProducter(myCollection);
        BreadConsumer breadConsumer = new BreadConsumer(myCollection);
        BreadConsumer breadConsumer1 = new BreadConsumer(myCollection);
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        executorService.execute(breadProducter);
        executorService.execute(breadProducter1);
        executorService.execute(breadConsumer);
        executorService.execute(breadConsumer1);
    }
}
